<template>
  <com-card>
    <div slot="com_header">
      <el-row>
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="searchObj.query"
            class="input-with-select"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="query"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4" style="margin-left: 20px">
          <el-button
            @click="tianjiaVisible = true"
            type="primary"
            icon="el-icon-circle-plus-outline"
            >添加</el-button
          >
        </el-col>
      </el-row>
    </div>
    <div slot="com_content">
      <el-row>
        <el-table :data="dataSource" border>
          <el-table-column type="index" label="序号"> </el-table-column>
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="email" label="邮箱地址"></el-table-column>
          <el-table-column prop="mobile" label="电话号码"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <template #default="{ row }">
              <el-switch
                v-model="row.mg_state"
                active-color="#409EFF"
                inactive-color="#ff4949"
                @change="setState(row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间">
          </el-table-column>
          <el-table-column label="操作" width="200px">
            <template #default="{ row }">
              <el-tooltip content="修改资料" placement="top">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="small"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除用户" placement="top">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  @click="del(row.id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="分配角色" placement="top">
                <el-button
                  type="warning"
                  icon="el-icon-s-tools"
                  size="small"
                  @click="setRole(row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="searchObj.pagenum"
            :page-sizes="[2, 4, 6, 8]"
            :page-size="searchObj.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-row>
      <!-- 分配角色弹窗 -->
      <el-dialog title="分配角色" :visible.sync="roleVisible" width="30%">
        <el-form>
          <el-form-item label="用户名:">
            {{ user.username }}
          </el-form-item>
          <el-form-item label="当前角色:">
            {{ user.role_name }}
          </el-form-item>
          <el-form-item label="分配角色:">
            <el-select v-model="roleId" placeholder="请选择">
              <el-option
                v-for="item in selectSource"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="gosetrole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加弹窗 -->
      <el-dialog title="提示" :visible.sync="tianjiaVisible" width="30%">
        <el-form
          label-width="70px"
          size="small"
          style="width: 270px"
          :model="abcObj"
          :rules="relus"
          ref="ruleForm"
        >
          <el-form-item label="用户名:" prop="username">
            <el-input type="text" v-model="abcObj.username"></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="password">
            <el-input type="text" v-model="abcObj.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input type="text" v-model="abcObj.email"></el-input>
          </el-form-item>
          <el-form-item label="电话号:" prop="mobile">
            <el-input type="text" v-model="abcObj.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="tianjiaVisible = false">取 消</el-button>
          <el-button type="primary" @click="doupdate()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </com-card>
</template>

<script>
import {
  api_query,
  api_state,
  api_setRole,
  api_users,
  api_del,
} from "../../api/user.js";
//获取角色的api
import { api_role_query,} from "../../api/role.js";
import ComCard from "../../components/comCard";
export default {
  components: {
    ComCard,
  },
  data() {
    //验证用户名
    let validateusername = (rule, value, callback) => {
      if (value) {
        let reg = /^[0-9a-z]{3,15}$/gi;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("用户名格式不对！"));
        }
      } else {
        callback(new Error("请输入用户名！"));
      }
    };
    //验证密码;
    let validatepassword = (rule, value, callback) => {
      if (value) {
        let reg = /^[0-9a-z]{3,9}$/gi;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("密码格式不对！"));
        }
      } else {
        callback(new Error("请输入密码！"));
      }
    };
    //验证邮箱
    let validateemail = (rule, value, callback) => {
      if (value) {
        let reg =
          /^([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?$/i;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("邮箱格式不对！"));
        }
      } else {
        callback(new Error("请输入邮箱！"));
      }
    };
    //验证手机号
    let validatemobile = (rule, value, callback) => {
      if (value) {
        let reg = /^[0-9]{11}$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("手机号格式不对！"));
        }
      } else {
        callback(new Error("请输入手机号！"));
      }
    };
    return {
      relus: {
        username: [{ validator: validateusername, trigger: "blur" }],
        password: [{ validator: validatepassword, trigger: "blur" }],
        email: [{ validator: validateemail, trigger: "blur" }],
        mobile: [{ validator: validatemobile, trigger: "blur" }],
      },
      roleId: "",
      //记录当前设置角色的用户
      user: {},
      //下拉框动态数据源
      selectSource: [],
      //控制角色分配的显示与隐藏
      roleVisible: false,
      //添加用户弹窗
      tianjiaVisible: false,
      searchObj: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      abcObj: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //总数据条数
      total: 0,
      //总数据列表
      dataSource: [],
    };
  },
  created() {
    this.query();
  },
  methods: {
    //添加用户
    doupdate() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let rst = await api_users(this.abcObj);
          let { status, msg } = rst.meta;
          if ((status = 201)) {
            this.tianjiaVisible = false;
            this.$message.success(msg);
            this.query();
            this.abcObj = {};
          }
        }
      });
    },
    //删除用户
    async del(id) {
      let rst = await api_del({ id });
      let { status, msg } = rst.meta;
      if (status == 200) {
        this.$message.success(msg);
        this.query();
      }
      console.log(rst);
    },
    //点击确定按钮触发的方法
    async gosetrole() {
      let rst = await api_setRole({ uId: this.user.id, rid: this.roleId });
      let { msg, status } = rst.meta;
      if (status == 200 || status == 400) {
        this.roleVisible = false;
        this.$message.success(msg);
        this.query();
      }
      console.log(rst);
    },
    //分配角色
    async setRole(row) {
      //获取所有角色的api
      let rst = await api_role_query();
      this.selectSource = rst.data;
      //记录当前的用户信息
      this.user = row;
      console.log(this.selectSource);
      this.roleVisible = true;
    },
    //当页发生变化触发的函数
    handleCurrentChange(pagenum) {
      this.searchObj.pagenum = pagenum;
      this.query();
    },
    //当条数发生变化触发的函数
    handleSizeChange(pagesize) {
      this.searchObj.pagesize = pagesize;
      this.query();
    },
    //修改用户状态
    async setState(row) {
      let rst = await api_state({ uId: row.id, type: row.mg_state });
      console.log(rst);
      let { status, msg } = rst.meta;
      if (status == 200) {
        let { username } = rst.data;
        this.$message.success(`用户:${username}${msg}`);
      }
    },
    //查询
    async query() {
      let rst = await api_query(this.searchObj);
      let { total, users } = rst.data;
      this.total = total;
      this.dataSource = users;
      console.log(this.dataSource);
    },
  },
};
</script>

<style lang="less" scoped>
</style>